package cn.cxj.basic.interceptor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

/**
 * 登陆拦截器
 * @author chenxinjie
 * @date 2022-2-7 23:56:26
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        // 校验请求头里面的token
        if (!StringUtils.isEmpty(token)) {
            // 根据token获取redis中的登陆信息
            Object loginTemp = redisTemplate.opsForValue().get(token);
            if (loginTemp != null) {
                // 刷新过期时间为30分钟
                redisTemplate.opsForValue().set(token, loginTemp, 30, TimeUnit.MINUTES);
                //@TODO 权限校验
                return true;
            }
        }
        // 如果token为空
        response.setContentType("application/json;charset=utf-8");
        response.setCharacterEncoding("UTF-8");
        PrintWriter writer = response.getWriter();
        writer.write("{\"success\" : false,\"message\":\"noLogin\"}");
        writer.close();
        return false;
    }
}
